#include "Puzzle.h"
#include "PuzzlePoint.h"
#include <MultiWidgets/FadeAnimator.hpp>

void Puzzle::init(){
	setFixed();
	//top middle
	auto point = MultiWidgets::create<PuzzlePoint>();
	point->setLocation(width()*337/672-2,height()*220/670-1);
	point->eventAddListener("clicked","clicked",this);
	addChild(point);
	//bottom middle
	point = MultiWidgets::create<PuzzlePoint>();
	point->setLocation(width()*337/672-2,height()*582/670-3);
	point->eventAddListener("clicked","clicked",this);
	addChild(point);
	//topleft
	point = MultiWidgets::create<PuzzlePoint>();
	point->setLocation(width()*163/672-2,height()*149/670-1);
	point->eventAddListener("clicked","clicked",this);
	addChild(point);
	//topright
	point = MultiWidgets::create<PuzzlePoint>();
	point->setLocation(width()*508/672-2,height()*149/670-1);
	point->eventAddListener("clicked","clicked",this);
	addChild(point);
	//bottomleft
	point = MultiWidgets::create<PuzzlePoint>();
	point->setLocation(width()*163/672-2,height()*467/670-3);
	point->eventAddListener("clicked","clicked",this);
	addChild(point);
	//bottomright
	point = MultiWidgets::create<PuzzlePoint>();
	point->setLocation(width()*508/672-2,height()*467/670-1);
	point->eventAddListener("clicked","clicked",this);
	addChild(point);
	//leftbottomtriangle
	point = MultiWidgets::create<PuzzlePoint>();
	point->setLocation(width()*205/672-2,height()*413/670-1);
	point->eventAddListener("clicked","clicked",this);
	addChild(point);
	//rightbottomtriangle
	point = MultiWidgets::create<PuzzlePoint>();
	point->setLocation(width()*468/672-2,height()*413/670-1);
	point->eventAddListener("clicked","clicked",this);
	addChild(point);


	numClicked =0;
}


void Puzzle::renderBackground(Luminous::RenderContext & r) const{

	Nimble::Vector2 center = 0.5f * size().toVector();
	Luminous::Style s;
    s.setStrokeColor(1,1,1,1);
    s.setStrokeWidth(1.5);
	float radius = height()/2;

	r.drawArc(center,radius-1,0,Nimble::Math::TWO_PI,s,50);
	Radiant::Color tempColor= backgroundColor();

}

bool Puzzle::isInside(Nimble::Vector2 v) const {

	Nimble::Vector2 center = 0.5f * size().toVector();

	double distance = (center - v).length();

	return distance < (height()/2);

}

void Puzzle::clicked(){
	numClicked++;

	if (numClicked >=8){
		MultiWidgets::FadeAnimator::fadeIn(*this, 0.3);
		eventSend("done");
	}

}

void Puzzle::eventProcess(const QByteArray & messageId, Radiant::BinaryData & data){

	if(messageId == "clicked") clicked();
}